import { get } from "../../utils/request";
const app = getApp();
Page({
  data: {
    lessons: [],
    filteredLessons: [],
    url: "",
  },
  async onLoad(options) {
    let { lesson: lessons } = await get("/lesson");
    this.setData({ lessons, filteredLessons: lessons }, () => {
      //在页面加载完成后，给lessons赋值之后，可以试着播放传递过来的视频
      this.playLesson();
    });
  },
  playLesson() {
    debugger;
    //先获取在页面跳转前保存好的课程ID
    let lessonId = app.globalData.lessonId;
    if (lessonId) {
      //找到此课程ID对应的对象
      let lesson = this.data.lessons.find((lesson) => lesson._id === lessonId);
      if (lesson) {
        //给url地址赋值就可以自动播放了
        this.setData({ url: lesson.url });
      }
      //因为此课程ID是临时变量，用一次就要清除了
      app.globalData.lessonId = "";
    }
  },
  onShow() {
    //当此页面重新显示出来的时候也要试图播放一次
    this.playLesson();
  },
  watch(event) {
    let { lesson } = event.mark;
    let { url } = lesson;
    this.setData({ url });
  },
  addFavorite(event) {
    //先获取当前要添加收藏的课程对象
    let { lesson } = event.mark;
    //再获取本地存储的课程对象
    const favorites = wx.getStorageSync("favorites") || {};
    //添加新的课程对象
    favorites[lesson._id] = lesson;
    //把最新的课程对象保存在本地存储中
    wx.setStorageSync("favorites", favorites);
  },
  handleSearch(event) {
    let { lessons } = this.data;
    //如果用户输入的内容为空
    if (event.detail === "") {
      this.setData({ filteredLessons: lessons });
    }
    //如果用户输入的关键字不为空
    this.setData({
      //给过滤后的lessons重新赋值，对原组进行过滤，只保留标题中包括关键字的课程
      filteredLessons: lessons.filter((lesson) =>
        lesson.title.includes(event.detail)
      ),
    });
  },
});
